<template>
	<view>
	  <button @click="handleGetSystemInfo">获取系统信息</button>
		<button @click="handleSetStorageSync">同步设置存储(key为name)</button>
		<button @click="handleGetStorageSync">同步获取缓存</button>
		<button @click="handleConnectSocket">连接websocket</button>
		<button @click="handleSendMsg">发送websocket消息</button>
	</view>
</template>

<script setup lang="ts">
import io from '@hyoga/uni-socket.io'
// 获取系统信息
const handleGetSystemInfo = () => {
	const systemInfo = uni.getSystemInfoSync()
	console.log(systemInfo)
}

// 同步设置存储
const handleSetStorageSync = () => {
	const time = +new Date()
	uni.setStorageSync('name', `小明${time}`)
}

// 获取设置的存储
const handleGetStorageSync = () => {
	const name = uni.getStorageSync('name')
	console.log('name', name)
}

const connectSocket = baseUrl => {
  return new Promise((resolve, reject) => {
    if (socket) {
      resolve(socket)
      return
    }
    // io('http://172.16.61.143:3000'
    socket = io(baseUrl, {
      query: {},
      transports: ['websocket'],
      timeout: 5000,
    })
    socket?.on('connect', () => {
      console.log('ws 已连接=====')
      resolve(socket)
    })
    socket?.on('error', msg => {
      console.log('ws error', msg)
      reject(msg)
    })
  })
}

let socket
const handleConnectSocket = async () => {
	socket = await connectSocket('http://localhost:3005')
}

// 发送事件消息到服务端
const handleSendMsg = () => {
	if (!socket) return
 	socket.emit('reportEvent', { page: 'homePage', eventName: 'click', eventParams: { name: 'hewang', time: +new Date() } }, rsp => {
		console.log(rsp)
	})
}
</script>

<style>
	       
</style>
